﻿// Jinx AJAX Framework
// Copyright (C) 2008 Blake Hegerle
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Formality.FormalSystem.Parser
{
    internal abstract class Expression<T>
    {
        public abstract T Convert(Func<string, IEnumerable<T>, T> Converter);
    }

    internal class Term<T> : Expression<T>
    {
        public readonly T Item;

        public Term(T t)
        {
            Item = t;
        }

        public override T Convert(Func<string, IEnumerable<T>, T> Converter)
        {
            return Item;
        }
    }

    internal class Operator<T> : Expression<T>
    {
        public readonly Operator Op;
        public readonly List<Expression<T>> Operands;

        internal Operator(Operator Operator)
        {
            Op = Operator;
            Operands = new List<Expression<T>>();
        }

        public int Precedence
        {
            get { return Op.Precedence; }
        }

        public void AddOperand(Expression<T> Operand)
        {
            Operands.Add(Operand);
        }

        public void AddOperands(IEnumerable<Expression<T>> AdditionalOperands)
        {
            Operands.AddRange(AdditionalOperands);
        }

        public override T Convert(Func<string, IEnumerable<T>, T> Converter)
        {
            return Converter(Op.CanonicalSymbol, from o in Operands select o.Convert(Converter));
        }
    }
}